package app.cn.com.school.fragment

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.widget.ImageView
import android.widget.Toast
import app.cn.com.school.R
import app.cn.com.school.activity.*
import app.cn.com.school.adapter.HomeImgAdapter
import app.cn.com.school.api.AppRequest
import app.cn.com.school.api.bean.response.IndexResponse
import app.cn.com.school.databinding.FragmentHomeBinding
import app.cn.com.school.view.ObservableScrollView
import app.cn.com.school.zixing.android.CaptureActivity
import app.cn.com.watering.api.ApiUtill
import com.bigkoo.convenientbanner.ConvenientBanner
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator
import com.bigkoo.convenientbanner.holder.Holder
import com.bigkoo.convenientbanner.listener.OnItemClickListener
import com.facebook.drawee.view.SimpleDraweeView

/**
 * Created by Administrator on 2017/11/1 0001.
 */
class HomeFragment : BaseFragment<FragmentHomeBinding>(), OnItemClickListener {
    override fun onItemClick(position: Int) {
       showTips("img ${position}")
    }

    override fun initBindingVar() {
    }

    var imageHeight: Int = 350
    var REQUEST_CODE_SCAN: Int = 0x0000
    var DECODED_CONTENT_KEY: String = "codedContent"
    var DECODED_BITMAP_KEY: String = "codedBitmap"
    var images = ArrayList<String>()
    var moreList = ArrayList<IndexResponse.DatasBean.GoodsBean>()
    var adapter: HomeImgAdapter? = null
    private var mParam1: String? = null
    private var mParam2: String? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (arguments != null) {
            mParam1 = arguments.getString(ARG_PARAM1)
            mParam2 = arguments.getString(ARG_PARAM2)
        }
    }

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        initBinding(R.layout.fragment_home, container)
        mView = binding.root
        indexHttp()
        initView()
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    private fun initView() {
        var vto = binding.banner.viewTreeObserver
        vto.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                binding.banner.viewTreeObserver.removeGlobalOnLayoutListener(this)
                binding.homeScrollView.setScrollViewListener(object : ObservableScrollView.ScrollViewListener {
                    override fun onScrollChanged(scrollView: ObservableScrollView, x: Int, y: Int, oldx: Int, oldy: Int) {
                        if (y <= 0) {
                            binding.homeTop.setBackgroundColor(Color.argb(0.toInt(), 0xfd, 0x91, 0x5b))
                        } else if (y > 0 && y <= imageHeight) {
                            val scale = y.toFloat() / imageHeight
                            val alpha = 255 * scale
                            // 只是layout背景透明(仿知乎滑动效果)白色透明
                            binding.homeTop.setBackgroundColor(Color.argb(alpha.toInt(), 0xfd, 0x91, 0x5b))
                        } else {
                            binding.homeTop.setBackgroundColor(Color.argb(255.toInt(), 0xfd, 0x91, 0x5b))
                        }

                    }

                })

            }

        })

        initClick()
    }


    private fun initClick() {
        //扫描二维码
        binding.imgZx.setOnClickListener {
            startActivityForResult(Intent(context, CaptureActivity::class.java), REQUEST_CODE_SCAN)
        }
        //消息
        binding.imgNews.setOnClickListener {
            startActivity(Intent(context, NewsActivity::class.java))
        }
        //精品文具
        binding.linStationery.setOnClickListener {
            startActivity(Intent(context, StationeryActivity::class.java).putExtra("type", "0"))
        }
        //学习冲浪
        binding.linSurfing.setOnClickListener {
            startActivity(Intent(context, StationeryActivity::class.java).putExtra("type", "1"))
        }
        //奇幻文字
        binding.linLetter.setOnClickListener {
            startActivity(Intent(context, StationeryActivity::class.java).putExtra("type", "2"))
        }
        //青春杂志
        binding.linMagazine.setOnClickListener {
            startActivity(Intent(context, StationeryActivity::class.java).putExtra("type", "3"))
        }
        //会员专区
        binding.linPrefecture.setOnClickListener {
            startActivity(Intent(context, PrefectureActivity::class.java))
        }

        //搜索
        binding.searchTop.setOnClickListener { startActivity(Intent(context, SearchActivity::class.java).putExtra("type", "0")) }
        binding.homeImgOne.setOnClickListener { startActivity(Intent(context, GoodsDetailsActivity::class.java)) }
        binding.homeImgTwo.setOnClickListener { startActivity(Intent(context, StoreDetailsActivity::class.java)) }

        if (adapter == null) {
            adapter = HomeImgAdapter(context, moreList)
            binding.homeListView.adapter = adapter
        }
        Handler().post { binding.homeScrollView.smoothScrollTo(0, 0) }
//        videoScrollview.scrollTo(10, 10);
//        scrollview.smoothScrollTo(0, 0);
//        scrollView.fullScroll(ScrollView.FOCUS_UP);滚动到顶部
    }


    /**
     * 首页请求数据
     * */
    private fun indexHttp() {
        ApiUtill.getInstance().getApi(AppRequest.getAPI().index(), { baseResponse ->
            baseResponse as IndexResponse
            if (baseResponse.code == 200) {
                for (r in baseResponse.datas.carousel) {
                    images.add(r.img)
                }
                imgsGo(images)
                binding.homeImgOne.setImageURI(baseResponse.datas.youxuan[0].img_url)
                binding.homeImgTwo.setImageURI(baseResponse.datas.youxuan[1].img_url)
                binding.homeImgVv.setImageURI(baseResponse.datas.youxuan[2].img_url)
                moreList.addAll(baseResponse.datas.goods)
                adapter!!.notifyDataSetChanged()
            } else {
                showTips("请求数据失败")
            }
        })
    }

    private fun imgsGo(images: List<String>) {
        //开始自动翻页
        binding.banner.setPages(CBViewHolderCreator { LocalImageHolderView() }, images)
                //设置指示器是否可见
                .setPointViewVisible(true)
                //设置自动切换（同时设置了切换时间间隔）
                .startTurning(2000)
                //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                .setPageIndicator(intArrayOf(R.mipmap.ic_page_indicator, R.mipmap.ic_page_indicator_focused))
                //设置指示器的方向（左、中、右）
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT)
                //设置点击监听事件
                .setOnItemClickListener(this)
                //设置手动影响（设置了该项无法手动切换）
                .isManualPageable = true
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_SCAN && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                val content = data.getStringExtra(DECODED_CONTENT_KEY)
                //返回生成的二维码
//                val bitmap = data.getParcelableExtra<Bitmap>(DECODED_BITMAP_KEY)
                Toast.makeText(context, "content:" + content, Toast.LENGTH_LONG).show()

            }
        }
    }

    open class LocalImageHolderView : Holder<String> {
        private lateinit var imageView: SimpleDraweeView
        override fun createView(context: Context?): View {
            imageView = SimpleDraweeView(context)
            imageView.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
            imageView.scaleType = ImageView.ScaleType.FIT_XY
            return imageView
        }

        override fun UpdateUI(context: Context?, position: Int, data: String?) {
            imageView.setImageURI(data)
        }
    }

    companion object {
        private val ARG_PARAM1 = "param1"
        private val ARG_PARAM2 = "param2"
        fun newInstance(param1: String, param2: String): HomeFragment {
            val fragment = HomeFragment()
            val args = Bundle()
            args.putString(ARG_PARAM1, param1)
            args.putString(ARG_PARAM2, param2)
            fragment.arguments = args
            return fragment
        }

    }

}